package com.itranswarp.learnjava.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.UUID;

public class DBUtil {
    private static Connection connection;

    /**
     * 初始化数据库连接
     */
    public static void init(String url, String user, String password) {
        try {
            Class.forName("com.mysql.jdbc.Driver"); // 5.x 写法
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("数据库连接初始化成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        return connection;
    }

    /**
     * 关闭连接（在项目关闭时调用）
     */
    public static void close() {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
                System.out.println("数据库连接已关闭。");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * uuid
     * @return
     */
    public static  String genUniqueString(){
        return  UUID.randomUUID().toString();
    }
}
